package com.vnp.vchat;

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.net.ssl.SSLContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.TransitionDrawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.vnp.vchat.Util.Common;
import com.vnp.vchat.Util.KeyboardHelper;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.bean.ObjContact;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.bean.ObjMsgChat;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;
import com.vnp.vchat.version2.CaidatmoiActivity;
import com.vnp.vchat.version2.DanhbaActivity;
import com.vnp.vchat.version2.KetnoiActivity;

@SuppressLint("NewApi")
public class MainActivity extends MyActivity {

	static TabHost tabHost;
	PreferenceHelper preferenceHelper;
	MySQLiteHelper db;
	Boolean backAgain = false;
	
	SocketIO socketIO;
	String URL = "http://w41.vnpgroup.net:8080";
//	String URL = "";
	
	
	MediaPlayer mp;
	
	boolean onPause = false;
	boolean onFinish = false;
	public static boolean onGoto = false;
	
	Handler mHandler = new Handler();
	
	// new msg
	ViewGroup viewNewMsg;
	TextView txtName, txtTinNhan;
	public static boolean isExit;
	
	Runnable rShow = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					viewNewMsg.setVisibility(View.VISIBLE);
					viewNewMsg.startAnimation(pullDown);			
				}
			});
		}
	};
	
	Runnable rHide = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					viewNewMsg.setVisibility(View.INVISIBLE);
					viewNewMsg.startAnimation(pullUp);
				}
			});
			
		}
	};
	
	
	
	Animation pullDown, pullUp;
	Thread tr;
	
	// check ket noi
	// layout ket noi
	RelativeLayout llKetnoi;
	TextView txtKetnoi;
	
	Runnable rHideKetnoi = new Runnable() {
		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					llKetnoi.setVisibility(View.GONE);
//					llKetnoi.setAnimation(pullUp);
				}
			});
			
		}
	};
	
	// gui intent disconnect
	private BroadcastReceiver mReceiver;
	
	// getContact
	ArrayList<ObjContact> objContacts = new ArrayList<ObjContact>();
	JSONObject jsonPhone = new JSONObject();
	String listContactJson;
	String type;
	
	ArrayList<String> list = new ArrayList<String>();
	
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		viewNewMsg = (ViewGroup) findViewById(R.id.ll_new_msg);
		txtName = (TextView) findViewById(R.id.txt_name);
		txtTinNhan = (TextView) findViewById(R.id.txt_msg);
		pullDown = AnimationUtils.loadAnimation(this, R.anim.slide_down);
		pullUp = AnimationUtils.loadAnimation(this, R.anim.slide_up);
		
		isExit = true;
		// check ket noi socket
		llKetnoi = (RelativeLayout) findViewById(R.id.ll_ketnoi);
		txtKetnoi = (TextView) findViewById(R.id.txt_ketnoi);
		
		preferenceHelper = new PreferenceHelper(this);
		db = new MySQLiteHelper(MainActivity.this);
		
		updateDeviceId();
		
		
		tabHost = getTabHost();
		setTabs();
		
		
		// huy ban phim khi chuyen tab
		tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			
			@Override
			public void onTabChanged(String tabId) {
				KeyboardHelper.hideSoftKeyboard(MainActivity.this);
			}
		});
		
//		URL = preferenceHelper.getDomainConnect()+preferenceHelper.getPostConnect();
		
		connectSocket();
		reciveBroadCast();
		setFont();
		
//		getContact();
		
		long t = Common.getCurrentTime() - preferenceHelper.getTimeGetContact() ;
		
		Log.i("DATA", "Thoi gian: "+t);
		if (t > 86400000){
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					Utils.getContact(MainActivity.this);
				}
			}).start();
		}
		
//		sendContactHttp();
		
	}
	
	private void setFont() {
		txtName.setTypeface(Utils.getTypefaceRegular(MainActivity.this));
		txtTinNhan.setTypeface(Utils.getTypefaceRegular(MainActivity.this));
		txtKetnoi.setTypeface(Utils.getTypefaceRegular(MainActivity.this));
	}
	
	private void playRingtone(){
		/*try {
			
			mp.prepare();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mp.start();*/
		/*Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
	    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
	    r.play();*/
		
		
		
		mp = MediaPlayer.create(MainActivity.this, R.raw.result);
		try {
			if (mp.isPlaying()){
				mp.stop();
				mp.release();
				mp = MediaPlayer.create(MainActivity.this, R.raw.result);
			}
			mp.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private void showAnimationNewMsg(String name, String content){
		mHandler.postDelayed(rShow, 300);
		txtName.setText(name);
		txtTinNhan.setText(content);
		mHandler.postDelayed(rHide, 3300);
	}
	
	public void setTabs(){
		addTab("Tin nhan", R.drawable.tab_tinnhan_selector, TinNhanActivity.class);
		addTab("Khach hang", R.drawable.tab_khachhang_selector, KhachhangActivity.class);
		addTab("Ket noi", R.drawable.tab_ketnoi_selector, KetnoiActivity.class);
		addTab("Danh ba", R.drawable.tab_danhba_selector, DanhbaActivity.class);
		addTab("Cai dat", R.drawable.tab_caidat_selector, CaidatmoiActivity.class);
	}
	
	private void addTab(String labelId, int drawableId, Class<?> c)
	{
		Intent intent = new Intent(this, c);
		TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);	

		View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
		ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
		icon.setImageResource(drawableId);

		spec.setIndicator(tabIndicator);
		spec.setContent(intent);
		tabHost.addTab(spec);
	}
	
	public static void hideTab() {
		tabHost.setVisibility(View.GONE);
		tabHost.getTabWidget().getChildAt(0).setVisibility(View.GONE);
		tabHost.getTabWidget().getChildAt(1).setVisibility(View.GONE);
		tabHost.getTabWidget().getChildAt(2).setVisibility(View.GONE);
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onPause() {
		super.onPause();
		Log.i("Socket", "ON PAUSE-----");
		onPause = true;
		
		if (onGoto == true){
			
		} else {
			if (socketIO != null){
				socketIO.disconnect();
				cancelHandler();
				if (tr != null){
					tr.interrupt();
				}
			}
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();
		Log.i("Socket", "ON RESUME-----");
		Log.i("Socket", "ONFISH: "+ onFinish +" ONGOTO: "+onGoto+" ONPAUSE: "+onPause);
		if (onPause == true){
			if (onGoto == true){
				onGoto = false;
			} else {
				connectSocket();
			}
		} else {
			
		}
		onPause = false;
	}
	
	
	

	public void connectSocket(){
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				llKetnoi.setVisibility(View.VISIBLE);
				llKetnoi.setBackgroundColor(getResources().getColor(R.color.color_cam));
				txtKetnoi.setText("Đang kết nối...");
				
				if (Common.onScreenChat == true){
					// send broadcast show dang ket noi
					Intent broadcastIntent = new Intent();
					broadcastIntent.setAction(Common.CONNECTTING);
					sendBroadcast(broadcastIntent);
				}
			}
		});
		
		tr = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					try {
						SocketIO.setDefaultSSLSocketFactory(SSLContext.getInstance("Default"));
					} catch (NoSuchAlgorithmException e1) {
						e1.printStackTrace();
					}
					
					socketIO = new SocketIO(URL);
					socketIO.connect(new IOCallback() {

						@Override
						public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
							Log.i("DATA", "nhay vao thang 1");
						}

						@Override
						public void onMessage(String arg0, IOAcknowledge arg1) {
							Log.i("DATA", "nhay vao thang 2");
						}

						@Override
						public void onError(SocketIOException message) {
							Log.e("Socket","ket noi bi loi----------:" + message.toString());
							if (tr != null){
								tr.interrupt();
							}
							connectSocket();
						}

						@Override
						public void onDisconnect() {
							Log.e("Socket", "Da dut ket noi----------");
							
							if (onFinish == true){
								runOnUiThread(new Runnable() {
									
									@Override
									public void run() {
										llKetnoi.setVisibility(View.VISIBLE);
										llKetnoi.setBackgroundColor(Color.BLACK);
										txtKetnoi.setText("Mất kết nối");											
									}
								});
							} else {
								if (onPause == true){
									
								} else {
									connectSocket();
								}
							}
							
						}

						@Override
						public void onConnect() {
							Log.e("Socket", "Ket noi thanh cong----------");
							socketIO.emit("join", preferenceHelper.getDataJoin());
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
											llKetnoi.setBackgroundResource(R.drawable.background_transition);
											TransitionDrawable background = (TransitionDrawable) llKetnoi.getBackground();
											background.startTransition(100);
											txtKetnoi.setText("Kết nối thành công!");
											mHandler.postDelayed(rHideKetnoi, 2000);
											if (Common.onScreenChat == true){
												// send broadcast da kn
												Intent broadcastIntent = new Intent();
												broadcastIntent.setAction(Common.CONNECTED);
												sendBroadcast(broadcastIntent);
											}
								}
							});
						}

						@Override
						public void on(String event, IOAcknowledge arg1, Object... args) {
							System.out
									.println("Server triggered event '" + event + "'");
							Object[] arguments = args;

							if (event.equals("chat")) {
									String json = arguments[0].toString();
									Log.i("vChat", "Json chat nhan dc: "+json.toString());
									try {
										JSONObject jos = new JSONObject(json);

										JSONObject jo = jos.getJSONObject("data");

										int sendId = jo.getInt("send_id");
										int id = jo.getInt("id");
										long vgc = jo.getLong("vgc_rand");
										
										/*if (String.valueOf(sendId).equals(preferenceHelper.getUserId())){
											Common.VGC = Common.getCurrentTime();
										}*/
										if (Common.VGC == 0){
											Common.VGC = Common.getCurrentTime();
										}
										
										Log.i("DATA", "VGC nhan dc: "+vgc + " VGC da gui: "+Common.VGC);
										// check vcg xem da co chua, neu co roi thi khong lam gi ca, tuong tu nhu cai sendid
										
										if (Common.VGC == vgc){
//										if (preferenceHelper.getUserId().equals(String.valueOf(sendId))){
											Log.i("DATA", "lap message-----------");
										} else {
											final String name = jo.getString("name");
											final String content = jo.getString("text");
											int time = jo.getInt("time");
											
											String type, urlImage;
											if (jo.has("type")){
												type = jo.getString("type");
												urlImage = content;
												if (type.equals("image")){
													type = "image";
													urlImage = content;
												} else {
													type = "text";
													urlImage = "";
												}
												
											} else {
												type = "text";
												urlImage = "";
											}
											// nguyen nhan co the laf o cho nay 
											String avatar = "";
											Log.i("DATA", "USER ID: "+preferenceHelper.getUserId()+" SendID: "+sendId);
											if (preferenceHelper.getUserId().equals(String.valueOf(sendId))){
												Log.i("DATA", "0--------------------");
											}else {
												Log.i("DATA", "0---------66666666666");
//												avatar = db.getUrlAvatar(String.valueOf(sendId));
											}
											
											Log.i("DATA", "1--------------------");
											
											ObjMsgChat objMsgChat = new ObjMsgChat();
											objMsgChat.setUrlImageKH(urlImage);
											objMsgChat.setFromId(String.valueOf(sendId));
											objMsgChat.setContent(content);
											objMsgChat.setUrlAvatarKhachhang(avatar);
											objMsgChat.setTenKhachHang(name);
											objMsgChat.setTime(time);
											objMsgChat.setType(type);
											objMsgChat.setId(String.valueOf(id));
											
											Log.i("DATA", "2--------------------");
											
											final ObjKhachhang objKhachhang = new ObjKhachhang();
											objKhachhang.setUrlAvatar(avatar);
											objKhachhang.setName(name);
											objKhachhang.setAddress("");
											objKhachhang.setDsDaxem("");
											objKhachhang.setId(String.valueOf(sendId));
											objKhachhang.setTxtWebsite("");
											objKhachhang.setOnline(1);
											objKhachhang.setUrlDangxem("");
											objKhachhang.setTimeLastMessage(String.valueOf(time));
											objKhachhang.setLastMessage(content);
											String msgId = String.valueOf(Common.getCurrentTime()/1000);
											db.insertMSG(objMsgChat, objMsgChat.getFromId(), Common.SENDED, msgId);
											
											
											Log.i("vChat", "Co o trong man hinh chat :"+Common.onScreenChat);
											
											
											if (Common.onScreenChat == true){
												Log.i("DATA", "IS CHATTING: "+Common.isChatting );
												if (Common.isChatting.equals(objMsgChat.getFromId())){
													// gui 1 broad cast cho thang msg
													Intent broadcastIntent = new Intent();
													broadcastIntent.setAction(Common.CHAT);
													sendBroadcast(broadcastIntent);
													db.updateLastMsg(objMsgChat, 0);
													
												} else {
													// xu li ds theiet bi tsi day
													if (preferenceHelper.getUserId().equals(String.valueOf(sendId))){
														if (Common.isChatting.equals(objMsgChat.getId())){
															Log.i("DATA", "Xu li add msg cua chinh minh tai day");
															db.insertMSG(objMsgChat, Common.isChatting, Common.SENDED, msgId);
															// gui 1 broad cast cho thang msg
															Intent broadcastIntent = new Intent();
															broadcastIntent.setAction(Common.MY_ADD);
															sendBroadcast(broadcastIntent);
															db.updateLastMsg(objMsgChat, 1);
														} else {
															
														}
														
													} else {
														// gui 1 broad cast cho thang msg
														Intent newMsg = new Intent();
														newMsg.putExtra("objMsg", objMsgChat);
														newMsg.putExtra("khachhang", objKhachhang);
														newMsg.setAction(Common.CHAT_NEWMSG);
														sendBroadcast(newMsg);
														db.updateLastMsg(objMsgChat, 1);
														Log.i("vChat", "send chat new msg cua nguoi dang ko chat");
													}
												}
											} else {
												if (preferenceHelper.getUserId().equals(String.valueOf(sendId))){
													db.updateLastMsg(objMsgChat, 1);
													Intent broadcastIntent = new Intent();
													broadcastIntent.setAction(Common.IS_RELOAD);
													sendBroadcast(broadcastIntent);
												} else {
													runOnUiThread(new Runnable() {
														@Override
														public void run() {
															mHandler.removeCallbacks(rHide);
															mHandler.removeCallbacks(rShow);
															
															if (viewNewMsg.getVisibility() == View.VISIBLE){
																viewNewMsg.setVisibility(View.GONE);
															}
															
															showAnimationNewMsg(name, content);
															playRingtone();
														}
													});
													
													viewNewMsg.setOnClickListener(new OnClickListener() {
														
														@Override
														public void onClick(View v) {
															Log.i("vChat", "Click vo thang moi");
															mHandler.removeCallbacks(rHide);
															mHandler.postDelayed(rHide, 200);
															MainActivity.onGoto = true;
															Intent t = new Intent(MainActivity.this, ChatActivity.class);
															t.putExtra("khachhang", objKhachhang);
															/*// send broadcast
															Intent t1 = new Intent();
															t1.setAction(Common.FINSH_CHAT);
															sendBroadcast(t1);*/
															startActivity(t);
														}
													});
													
													db.updateHischat(objKhachhang);
													
													Intent t = new Intent();
													t.setAction(Common.ADD);
													sendBroadcast(t);
													
													db.updateLastMsg(objMsgChat, 1);
													
													Intent newMsg = new Intent();
													newMsg.setAction(Common.IS_READ);
													sendBroadcast(newMsg);
													
													Log.i("vChat", "update trang thai chua doc cho msg");
												}
											}
										}
										
										
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							} 
							
							if (event.equals("supplier")) {
								Log.i("vChat", "Supplier-----------------");
								String json = arguments[0].toString();
								Log.i("vChat", json.toString());
								try {
									JSONObject jos = new JSONObject(json);
									JSONObject data = jos.getJSONObject("data");
									
									int uid = data.getInt("uid");
									
									
									// khong tra ve uname
									String uname, avatar, city, pname, urlDangxem ;
									if (data.has("uname")){
										if (!data.getString("uname").equals("")){
											uname = data.getString("uname");
										} else {
											uname = "Khách - "+ String.valueOf(uid);
										}
									} else {
										uname = "Khách - "+ String.valueOf(uid);
									}
									
									
									if (data.has("avatar")){
										if (!data.getString("avatar").equals("")){
											avatar = data.getString("avatar");
										} else {
											avatar = "";
										}
									} else {
										avatar = "";
									}
									
									if (data.has("city")){
										if (!data.getString("city").equals("")){
											city = data.getString("city");
										} else {
											city = data.getString("ip");
										}
									} else {
										city = data.getString("ip");
									}
									
									String txtWebsite = data.getString("source");
									
									String txtWebsiteR = txtWebsite.replace("www.", "");
									
									if (data.has("pname")){
										if (!data.getString("pname").equals("")){
											pname = data.getString("pname");
											urlDangxem = data.getString("url");
										} else {
											pname = "";
											urlDangxem = data.getString("url");
										}
									} else {
										pname = "";
										urlDangxem = data.getString("url");
									}
									
									urlDangxem = data.getString("url");
									
									ObjKhachhang objKhachhang = new ObjKhachhang();
									
									objKhachhang.setUrlAvatar(avatar);
									objKhachhang.setName(uname);
									objKhachhang.setAddress(city);
									objKhachhang.setDsDaxem(pname);
									objKhachhang.setId(String.valueOf(uid));
									objKhachhang.setTxtWebsite(txtWebsiteR);
									objKhachhang.setOnline(1);
									objKhachhang.setUrlDangxem("http://"+txtWebsite+urlDangxem);
									
									int size = db.getUID(objKhachhang.getId()).size();
									ArrayList<String> listUid = db.getUID(objKhachhang.getId());
									
									Log.i("vChat", "So ban ghi:"+size);
									Log.i("vChat", "ID khach hang: "+objKhachhang.getId());
									
									for (int i = 0; i < listUid.size(); i++) {
										if (objKhachhang.getId().equals(listUid.get(i))){
											db.deleteKH(objKhachhang.getId());
											Log.i("vChat", "Xoa de update");
//											db.insertKH(objKhachhang, objKhachhang.getId());
										}
									}
								
									db.insertKH(objKhachhang, String.valueOf(uid));
									Log.i("vChat", "Insert moi");
									
										
									
									// gui 1 broad cast cho thang kh
									Intent broadcastIntent = new Intent();
									broadcastIntent.setAction("com.app.vchat.REFRESH");
									sendBroadcast(broadcastIntent);
								
									
									
								} catch (Exception e) {
									e.printStackTrace();
								}
								
							} 
						}
					});
				} catch (MalformedURLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		
		tr.start();
	}
	
	private void updateDeviceId(){
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				Log.i("vChat", "Khong update duoc");
			}

			@Override
			public void onSuccess(JSONObject re) {
				Log.i("DATA", "Update device: "+re.toString());
				try {
					String error = re.getString("error");
					if (error.equals("")){
						Log.i("vChat", "Update device thanh cong---------------s");
					} else {
						Log.i("vChat", "Update device that bai");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
		
		httpClientHelper.updateDeviceID(Integer.valueOf(preferenceHelper.getUserId()), preferenceHelper.getHash(), "ANDROID", preferenceHelper.getDeviceId(), Utils.getIMEI(MainActivity.this));
	}

	@Override
	public void onBackPressed() {
		if(backAgain==false) {
			backAgain = true;
			mHandler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					backAgain = false;
				}
			}, 2000);
		} else {
			backAgain = false;
			finish();
		}
		isExit = true;
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onDestroy() {
		super.onDestroy();
		cancelHandler();
		onFinish = true;
		if (tr != null){
			tr.interrupt();
		}
		
		try {
			mp.release();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		unregisterReceiver(mReceiver);
		
		
		
		if (isExit == true){
			Log.i("DATA", "thoat he thong hoan toan");
			System.exit(0);
			isExit = false;
		} else {
			
		}
//		System.exit(0);
		Log.i("vChat", "ONDESTROY");
	}
	
	private void cancelHandler(){
		try {
			if(socketIO != null){
				socketIO.disconnect();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		mHandler.removeCallbacks(rHide);
		mHandler.removeCallbacks(rShow);
		mHandler.removeCallbacks(rHideKetnoi);
		mHandler.removeCallbacksAndMessages(null);
	}
	
	private void reciveBroadCast(){
		IntentFilter intentFilter = new IntentFilter();
		
		
		 intentFilter.addAction(Common.DISCONECT);
		 intentFilter.addAction(Common.CONNECT);
		 intentFilter.addAction("THOAT");
		    
		    mReceiver = new BroadcastReceiver() {
				
				@Override
				public void onReceive(Context context, final Intent intent) {
					String action = intent.getAction();
					if (action.equals(Common.DISCONECT)){
						socketIO.disconnect();
						ChatActivity.onShow = false;
						Log.i("vChat", "Nhan duoc broadcast disconnect");
					} else if (action.equals(Common.CONNECT)) {
						if (tr != null){
							tr.interrupt();
						}
						connectSocket();
						Log.i("vChat", "Nhan duoc broadcast connect");
					} else if (action.equals("THOAT")) {
						finish();
					}
					
				}
			};
			
			// register
			this.registerReceiver(mReceiver, intentFilter);
	}
	
	
	// demo getAccount by phone
	public void getAccount(String phone){
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				Log.i("DATA", "GET ACCOUNT: "+error.toString());
			}

			@Override
			public void onSuccess(JSONObject re) {
				Log.i("DATA", "GET ACCOUNT: "+re.toString());
			}
			
			
			
		});
		
		httpClientHelper.getAccountByPhone(phone);
	}
	
	
	private class ReadContact extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			return null;
		}
		
	}
	
	void getContact(){
		ContentResolver cr = getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
				null, null, null);
		JSONArray block = new JSONArray();// clear phone list
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				
				ObjContact objContact = new ObjContact(); 
				
				String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
				String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

					Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ " = ?", new String[] { id }, null);
					String result = null;
					while (pCur.moveToNext()) {
						String phoneNo = pCur
								.getString(pCur
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						result = phoneNo.replaceAll("\\(", "").replaceAll(" ","").replaceAll("\\)", "").replaceAll("-", "").replace("+", "");
						
						
						block.put(result);
						objContact.setPhone(result);
						
					}
					pCur.close();
					pCur = null;
					
					/*objContact.setId(id);
					objContact.setName(name);
					
					objContacts.add(objContact);*/
					list.add(result);

				}
			}
			for (int i = 0; i < list.size(); i++) {
				Log.i("CONTACT", "Contact: "+list.get(i));
			}
			
			sendContactHttp();
			
		} else {
			Log.i("CONTACT", "KHONG CO LIEN LAC");
		}
		cur.close();
		cur = null;
	}
	
	void sendContactHttp(){
		
		
		list = db.getPhoneFromDB();
		
		JSONArray jsonArray = new JSONArray(list);
		
		/*for (int i = 0; i < objContacts.size(); i++) {
			jsonArray.put(objContacts.get(i).getJSONObject());
		}*/
		
		
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				Log.i("DATA", "Cap nhat danh ba loi");
			}

			@Override
			public void onSuccess(JSONObject re) {
				Log.i("DATA", "Cap nhat danh ba thanh cong :"+re.toString());
			}
			
		});
		
		
		httpClientHelper.sendContact(preferenceHelper.getAdminId(), jsonArray, preferenceHelper.getHashSetting());
	}
	
	
}
